//
//  YCCollectionViewFlowLayout.m
//  TitleContent
//
//  Created by 唐可雄 on 2019/7/20.
//  Copyright © 2019 swustyc. All rights reserved.
//

#import "YCCollectionViewFlowLayout.h"

@interface YCCollectionViewFlowLayout () {
    BOOL _didCaculateForAlign;  ///< 是否已经为对齐做了计算
}

@end

@implementation YCCollectionViewFlowLayout

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSArray<UICollectionViewLayoutAttributes *> *attrs = [super layoutAttributesForElementsInRect:rect];

    if (!_didCaculateForAlign) {
        CGFloat widthUse = CGRectGetMaxX(attrs.lastObject.frame) - CGRectGetMinX(attrs.firstObject.frame);
        CGFloat widthLeft = self.collectionView.bounds.size.width - widthUse;
        CGFloat insetLeft = 0;
        if (self.alignment == YCCollectionViewCellAlignmentLeft) {
            insetLeft = 0;
        } else if (self.alignment == YCCollectionViewCellAlignmentCenter) {
            insetLeft = widthLeft / 2.f;
        } else if (self.alignment == YCCollectionViewCellAlignmentRight) {
            insetLeft = widthLeft;
        }
        if (insetLeft < 0) {
            insetLeft = 0;
        }
        self.sectionInset = UIEdgeInsetsMake(self.originEdgeInsets.top, insetLeft + self.originEdgeInsets.left, self.originEdgeInsets.bottom, self.originEdgeInsets.right);
        // 标记
        _didCaculateForAlign = YES;
        // 重新计算
        return [super layoutAttributesForElementsInRect:rect];
    }

    return attrs;
}

@end
